import logging

import pymysql


class DBUtil:
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2021",
                                       database="ihrm", charset="utf8")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls, sql):
        cursor = None
        resp = None
        try:
            conn = cls.__get_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            resp = cursor.fetchone()
        except Exception as err:
            logging.info(f"查询出错：{str(err)}")
        finally:
            # 关闭游标
            cursor.close()
            cls.__close_conn()

        return resp

    @classmethod
    def cud_db(cls, sql):
        cursor = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            logging.info(f"影响的行数：{cls.conn.affected_rows()}")
            cls.conn.commit()
        except Exception as err:
            logging.info(f"正删改执行出错：{str(err)}")
            cls.conn.rollback()

        finally:
            cursor.close()
            cls.__close_conn()


if __name__ == '__main__':
    # print(DBUtil.select_one("select * from sys_org "))
    DBUtil.cud_db("update sys_org set name='其他' where id=13")
